package com.lin.game.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.lin.game.entity.User;
import com.lin.game.service.IUserService;
import com.lin.game.utils.MapCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {
    @Autowired
    private IUserService userService;

    @Autowired
    private DefaultKaptcha kaptcha;
    private Map<String,String> codeMap=new HashMap<>();

    @RequestMapping("/register")
    public int register(User user){
        System.out.println("获取参数："+user);
        int result =userService.register(user);
        return result;
    }
    @RequestMapping("/login")
    public User login(String username, String password, String code, String codekey){

        //获取服务生成的验证码
        String serverCode = codeMap.get(codekey);
        if (!code.equals(serverCode)) {
            User user = new User();
            user.setUsername("-1");
            return user;
        }

        //验证码匹配正常，删除map中保存的验证码
        codeMap.remove(codekey);

        //user不为null，说明用户登录成功
        //user为null，说明用户名或者密码错误
        User user = userService.login(username, password);
        return user;
    }
    @RequestMapping("/code")
    public void createCode(String codekey,HttpServletResponse response) throws IOException {
        String code=kaptcha.createText();
        codeMap.put(codekey,code);
        BufferedImage image=kaptcha.createImage(code);
        ImageIO.write(image,"jpg",response.getOutputStream());
    }
    @RequestMapping("/sendEmailCode")
    public int sendEmailCode(String username){
        int result = userService.sendEmailByUserName(username);
        return result;
    }
    @RequestMapping("/updatePassword")
    public  int updatePassword(String username,String newpassword,String code){
        //检验验证码
        String oldCode=MapCodeUtils.getCode(username);
        if (oldCode==null){
            //无效或已过期的验证码
            return -1;
        }
        if(!oldCode.equals(code)){
            return -2;
        }
        int result= userService.updatePassword(username,newpassword);
        MapCodeUtils.removeCode(username);
        return  result;
    }
}
